//
//  MeSuggestViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/16.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "MeSuggestViewController.h"
#import "YQBPlaceTextView.h"
#import  "CustomImagePickUtility.h"
#import "UserRes.h"
@interface MeSuggestViewController ()<UITextViewDelegate>
@property  (nonatomic, strong) UITextField *mobileField;
@property (nonatomic, strong) YQBPlaceTextView *iWantBuyTextf;// 建议
@property (nonatomic, strong) UIView *imgsView;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic) NSInteger selectIndex;
@property (nonatomic, strong) NSMutableArray *imgAry;
@property (nonatomic) float width;
//@property (nonatomic, strong) NSString *wenziNum;
//@property (nonatomic, strong) NSString *tupianNum;
@property (nonatomic, strong) UILabel *wenziLabel;
@property (nonatomic, strong) UILabel *tupianLabel;
@end

#define DELBTN 1000
#define IMGAEBTN 10000
@implementation MeSuggestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title  = @"意见和反馈";
     self.width = (BOUNDWIDTH-30-40)/5;
//    self.wenziNum = @"0";
//    self.tupianNum = @"0";
    [self createUI];
    [self setNaviDefaultRightBtnWithTitle:@"完成" andSel:@selector(handleCompleteAction)];
    // Do any additional setup after loading the view.
}


- (void)handleCompleteAction
{
    if ([CommonMethod isBlankString:self.mobileField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入联系方式"];
        return ;
    }
    if ([CommonMethod isBlankString:self.iWantBuyTextf.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入建议"];
        
        return ;
    }
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"TOKEN":user.TOKEN,
                             @"USERNAME":user.mobile,
                             @"WZNR00":self.iWantBuyTextf.text,
                             @"LXFS00":self.mobileField.text
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_59 params:params md5Paraname:@"" success:^(id  _Nullable response) {
        
       
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [SVProgressHUD dismiss];
//        });
      
        NSDictionary *result =  response;
        
        [self uploadImgs:[result objectForKey:@"ID"]];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
    }];
    
}

- (void)uploadImgs:(NSString *)suggestId
{
    if (self.imgAry.count == 0) {
        [self.navigationController popViewControllerAnimated:YES];
        [SVProgressHUD showInfoWithStatus:@"提交成功,谢谢您的意见"];
        return;
    }
    [self.imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        
        UserRes *user = [CommonMethod getUser];
        if (!user) {
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
            return;
        }
        
        UIImage *uploadImage  =  self.imgAry[0];
        NSData *oridata = UIImageJPEGRepresentation(uploadImage, 1);
        NSData *data =  nil;
        NSLog(@"dsds大小%ld",[oridata length]/1024/1024);
        if (([oridata length]/1024/1024)> 1) {
            data = UIImageJPEGRepresentation(uploadImage, 0.3);
        } else {
            data = oridata;
        }
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

        
        NSDictionary *params = @{
                                 @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                                 @"TOKEN":user.TOKEN,
                                 @"USERNAME":user.mobile,
                                 @"FEEDBACK_ID":suggestId,
                                 @"IMGSTR":encodedImageStr,
                                 @"HZM000":@"jpg"
                                 };
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showWithStatus:nil];
        });
        
        [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_60 params:params md5Paraname:@"" success:^(id  _Nullable response) {
            
            
            if ((self.imgAry.count-1) == idx) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                dispatch_async(dispatch_get_main_queue(), ^{
                           [SVProgressHUD showInfoWithStatus:@"提交成功,谢谢您的意见"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
          
                [self.navigationController popViewControllerAnimated:YES];
            }
            
       
            
        } fail:^(NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            });
        }];
        
    }];
    
}


-  (void)handleAddAction
{
    [CustomImagePickUtility showSheet:self andTitle:@"选择图片" andImageCount:5-self.imgAry.count WithEditCamera:YES];
    
}

#pragma mark -------------CustomImagePickUtilityDelegate
- (void)pickPhotoWithImage:(NSArray *)imgsAry{
    
    if (imgsAry.count ==0) {
        return;
    }
    
    [self.imgAry addObjectsFromArray:imgsAry];
    [self updateImgsView];
    
//
//    UIImage *uploadImage  =  imgsAry[0];
//    NSData *data = UIImageJPEGRepresentation(uploadImage, 0.3);
//    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
    


- (void)updateImgsView
{
    self.tupianLabel.text = [NSString stringWithFormat:@"%lu/5",self.imgAry.count];
    
    [self.imgsView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UIImageView class]]) {
            [obj removeFromSuperview];
        }
    }];
    if (self.imgAry.count == 0) {
        self.addBtn.frame = CGRectMake(15+(self.width+10)*self.imgAry.count, 0, self.width, self.width);
        return;
    }
    
  
    
    [self.imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [btn setBackgroundImage:obj forState:UIControlStateNormal];
//        btn.frame = CGRectMake(15+(self.width+10)*idx, 0, self.width, self.width);
//        [self.imgsView addSubview:btn];
        UIImageView *imageView = [UIImageView new];
        imageView.image = obj;
        imageView.userInteractionEnabled = YES;
        imageView.tag  = IMGAEBTN + idx;
        imageView.frame = CGRectMake(15+(self.width+10)*idx, 0, self.width, self.width);
        [self.imgsView addSubview:imageView];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"suggest_del"] forState:UIControlStateNormal];
        btn.frame = CGRectMake(self.width-20, -20, 40, 40);
        btn.tag  = DELBTN + idx;
        [btn addTarget:self action:@selector(handleDelAction:) forControlEvents:UIControlEventTouchUpInside];
        [imageView addSubview:btn];

    
    }];
    if (self.imgAry.count<5) {
        self.addBtn.frame = CGRectMake(15+(self.width+10)*self.imgAry.count, 0, self.width, self.width);
    }
    
}

- (void)handleDelAction:(id)sender
{
    UIButton  *btn = sender;
    NSInteger tag = btn.tag - DELBTN;
    UIImageView  *imageView = [self.view viewWithTag:tag+IMGAEBTN];
    [self.imgAry removeObject:imageView.image];
    [self  updateImgsView];
    
}


-  (NSMutableArray *)imgAry
{
    if (!_imgAry) {
        _imgAry = [NSMutableArray new];
    }
    return _imgAry;
    
}
-  (void)createUI
{
    UILabel *mobileText = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 100, 20)];
    mobileText.text  = @"联系方式";
    mobileText.textColor = RGB(51, 51, 51);
    mobileText.font = FONT_SIZE(16);
    [self.view addSubview:mobileText];
    
    self.mobileField  = [[UITextField alloc] initWithFrame:CGRectMake(140, 10, BOUNDWIDTH - 155, 20)];
    self.mobileField.placeholder  = @"请输入您的qq号或者手机号" ;
    self.mobileField.textAlignment = NSTextAlignmentRight;
    self.mobileField.font = FONT_SIZE(14);
    [self.view addSubview:self.mobileField];
    
    UserRes *user  = [CommonMethod getUser];
    if(user) {
        self.mobileField.text = user.mobile;
    }
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, BOUNDWIDTH, 0.5)];
    lineLabel.backgroundColor = Common_SepeColor;
    [self.view addSubview:lineLabel];
    
    UILabel *questionText = [[UILabel alloc] initWithFrame:CGRectMake(15, 50, 100, 20)];
    questionText.text  = @"问题描述";
    questionText.textColor = RGB(51, 51, 51);
    questionText.font = FONT_SIZE(16);
    [self.view addSubview:questionText];
    
    
    UIView *textBGView = [UIView new];
    textBGView.backgroundColor = [UIColor whiteColor];
    textBGView.frame = CGRectMake(15, 80, BOUNDWIDTH -30, 140);
    [self.view addSubview:textBGView];
    
    self.iWantBuyTextf = [[YQBPlaceTextView alloc]init];
    self.iWantBuyTextf.frame = CGRectMake(5, 5, BOUNDWIDTH-40, 115);
    self.iWantBuyTextf.font = FONT_SIZE(14);
    self.iWantBuyTextf.textColor = Common_TextColor;
    self.iWantBuyTextf.delegate = self;
    self.iWantBuyTextf.placeholder = @"如果您有什么问题或意见、想法和期望，请告诉我们";
    [textBGView addSubview:self.iWantBuyTextf];
    
    self.wenziLabel = [[UILabel alloc] initWithFrame:CGRectMake(BOUNDWIDTH- 105, 120, 60, 20)];
    self.wenziLabel.text  = @"0/500";
    self.wenziLabel.textColor = RGB(51, 51, 51);
    self.wenziLabel.font = FONT_SIZE(12);
    self.wenziLabel.textAlignment = NSTextAlignmentRight;
    [textBGView addSubview:self.wenziLabel];
    
    
    self.imgsView = [[UIView alloc] initWithFrame:CGRectMake(0, 240, BOUNDWIDTH, self.width)];
    [self.view addSubview:self.imgsView];
    
    
    self.tupianLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 260+self.width, 60, 15)];
    self.tupianLabel.text  = @"0/5";
    self.tupianLabel.textColor = Common_HeadTitle_Color;
    self.tupianLabel.font = FONT_SIZE(12);
    self.tupianLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.tupianLabel];
   
    
    self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addBtn setBackgroundImage:[UIImage imageNamed:@"suggest_add"] forState:UIControlStateNormal];
    self.addBtn.frame = CGRectMake(15, 0, self.width, self.width);
    [self.addBtn addTarget:self action:@selector(handleAddAction) forControlEvents:UIControlEventTouchUpInside];
    [self.imgsView addSubview:self.addBtn];
    
    
}


#pragma mark - TextViewDelegate
//输入时自动删除占位文字
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"";
    }
}

//当编辑时动态判断是否超过规定字数，这里限制20字
- (void)textViewDidChange:(UITextField *)textView{
    
    if (textView.text.length > 500) {
        textView.text = [textView.text substringToIndex:500];
    }
    //这里的_strLengthLbl为动态显示已输入字数，可按情况添加
    self.wenziLabel.text = [NSString stringWithFormat:@"%lu/500",textView.text.length];
}

//编辑结束后如内存为空自动添加占位文字
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"占位文字";
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
